#!/usr/bin/python
# -*- coding: UTF-8 -*-

################################################################################
#
# Copyright (c) 2020 openEuler.org, Inc. All Rights Reserved
#
################################################################################
"""
The maintainer for crawling yaml data

Authors: xiaojianghui
Date:    10/22/2020 11:01 AM
"""

import yaml
import requests
from dbConnecttion import MysqlConn
import time
import os


class Task(object):
    """
        download task for sig
    """

    def __init__(self):
        """
            init object
        """
        pass

    @staticmethod
    def download():
        """
            download detail
        """
        url = "https://gitee.com/openeuler/community/raw/master/sig/sigs.yaml"
        try:
            r = requests.get(url)
        except requests.exceptions.ConnectionError:
            print('ConnectionError')
            return
        except requests.exceptions.ChunkedEncodingError:
            print('ChunkedEncodingError')
            return
        with open("sigs.yaml", "wb") as code:
            code.write(r.content)

    @staticmethod
    def read():
        """
            read file
        """
        if os.path.exists("sigs.yaml"):
            with open("sigs.yaml", "r") as f:
                data = yaml.safe_load(f)
            if data and data['sigs']:
                mysql = MysqlConn.Mysql()
                for sig in data['sigs']:
                    sql = "select group_id from cve_git_repo_groups where group_name=%s"
                    val = (sig['name'],)
                    group_id = mysql.getOne(sql, val)['group_id']
                    # Delete data according to group_id to avoid duplication
                    sql1 = "delete from cve_gite_repo where group_id = %s"
                    val1 = (group_id,)
                    mysql.delete(sql1, val1)
                    mysql.dispose()
                    for p in sig["repositories"]:
                        org_path = p[0:p.rfind("/")]
                        path = p[p.rfind("/"):][1:]
                        create_time = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                        sql = "insert into cve_gite_repo (group_id, org_path, path, status, " \
                              "create_time) values (%s, %s, %s, %s, %s)"
                        val = (group_id, org_path, path, 0, create_time)
                        mysql.insertOne(sql, val)
                        mysql.dispose()
                mysql.close()
            os.remove("sigs.yaml")
